package com.factorit.security;

import java.security.Principal;

import org.securityfilter.realm.SimpleSecurityRealmBase;

import com.factorit.beans.User;
import com.factorit.business.dao.UserDao;
import com.factorit.spring.SessionContext;


public class SessionSecurityRealm extends SimpleSecurityRealmBase {
	//private static final transient Logger logger = Logger.getLogger(FitSecurityRealm.class);
   
	/**
    * Authenticate a user.
    *
    * Implement this method in a subclass to avoid dealing with Principal objects.
    *
    * @param username a username
    * @param password a plain text password, as entered by the user
    *
    * @return null if the user cannot be authenticated, otherwise a Pricipal object is returned
    */
	
   public Principal authenticate(String username, String password) {
	   SessionPrincipal principal = null;
   	   SessionContext context = SessionContext.getInstance();
	   UserDao userDao = (UserDao)context.getBean("userDao");
	   User user = userDao.getUserByUsernameAndPassword(username, password);
	   if(user != null){
		   if(principal != null){
			   principal = null;
		   }
		   principal = new SessionPrincipal(username,password,user);   
	   }
		   
	   return principal; 
   }
   
   /**
    * Implement this method in a subclass to avoid dealing with Principal objects.
    *
    * @param username The name of the user
    * @param role name of a role to test for membership
    * @return true if the user is in the role, false otherwise
    */
	/*public boolean isUserInRole(Principal username, String role) {
		
		SatPrincipal principal = (SatPrincipal) username;
		Employee e = principal.getUser();
		//Iterate over roles
		for(Role r : e.getRoles()){
			if(role.trim().equals(r.getName().trim())){
				return true;
			}
		}
		return false;
	}*/

}

